/**
 * Chart2D, a java library for drawing two dimensional charts.
 * Copyright (C) 2001 Jason J. Simas
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * The author of this library may be contacted at:
 * E-mail:  jjsimas@users.sourceforge.net
 * Street Address:  J J Simas, 887 Tico Road, Ojai, CA 93023-3555 USA
 */

package pos.reports;

import pos.interfaces.Messages;
import net.sourceforge.chart2d.Object2DProperties;
import net.sourceforge.chart2d.Chart2DProperties;
import net.sourceforge.chart2d.MultiColorsProperties;
import net.sourceforge.chart2d.PieChart2DProperties;
import net.sourceforge.chart2d.LegendProperties;
import net.sourceforge.chart2d.Dataset;
import net.sourceforge.chart2d.PieChart2D;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JApplet;
import javax.swing.JFrame;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import pos.interfaces.Database;
import pos.storage.StorageFactory;

/**
 *
 * @author Parvez
 */
public class SalesPieChart extends JApplet {
    private JFrame frame = null;
    private static boolean isApplet = true;
    private static Connection adminConn = null;
    
    private int rows;
    private String[] cols = null;
    private float[] vals = null;
    
    private String reportTitle = null;
    private String reportQuery = null;
    private String queryNumOfRows = null;
    private String param1 = null;
    private String param2 = null;
    
    /**
     * 
     * @param title String name of the chart
     * @param query String query to be executed
     * @param rows returned by the query
     * @param param1 String
     * @param param2 String 
     */
    public SalesPieChart(String title, String query, String rows, String param1, String param2) {
        this.reportTitle = title;
        this.reportQuery = query;
        this.queryNumOfRows = rows;
        this.param1 = param1;
        this.param2 = param2;
    }
    
    /**
     * For running as an application.
     * Calls init() and start().
     * 
     * @param title the chart title
     * @param query the query to be executed to get data
     * @param rows the query to get number of rows in the query
     * @param param1 first column of or query result (fields)
     * @param param2 second column of query results (values)
     */
    public void create () {
        this.isApplet = false;
//        SalesPieChart demo = new SalesPieChart();
        this.init();
        this.start();
    }


    /**
    * Configure the chart and frame, and open the frame.
    */
    @Override
    public void init() {

        //<-- Begin Chart2D configuration -->

        //Configure object properties
        Object2DProperties object2DProps = new Object2DProperties();
        object2DProps.setObjectTitleText (this.reportTitle);//needs to be a variable

        //Configure chart properties
        Chart2DProperties chart2DProps = new Chart2DProperties();
        chart2DProps.setChartDataLabelsPrecision (-3);

        //Configure legend properties
        this.query();
        LegendProperties legendProps = new LegendProperties();
        String[] legendLabels = this.cols;
//        {"Vancouver", "Barnaby", "North Vancouver", "Richmond", "Surrey", "New Westminister"};
        legendProps.setLegendLabelsTexts (legendLabels);

        //Configure dataset
        int numSets = this.rows, numCats = 1, numItems = 1;
        Dataset dataset = new Dataset (numSets, numCats, numItems);
        for(int i = 0; i < this.rows; i++) {
//            System.out.println(this.vals[i]);
            dataset.set (i, 0, 0, this.vals[i]);
        }
//        dataset.set (0, 0, 0, .419f);
//        dataset.set (1, 0, 0, .284f);
//        dataset.set (2, 0, 0, .284f);
//        dataset.set (3, 0, 0, .714f);
//        dataset.set (4, 0, 0, .193f);
//        dataset.set (5, 0, 0, .241f);

        //Configure graph component colors
        MultiColorsProperties multiColorsProps = new MultiColorsProperties();

        //Configure pie area
        PieChart2DProperties pieChart2DProps = new PieChart2DProperties();

        //Configure chart
        PieChart2D chart2D = new PieChart2D();
        chart2D.setObject2DProperties (object2DProps);
        chart2D.setChart2DProperties (chart2DProps);
        chart2D.setLegendProperties (legendProps);
        chart2D.setDataset (dataset);
        chart2D.setMultiColorsProperties (multiColorsProps);
        chart2D.setPieChart2DProperties (pieChart2DProps);

        //Optional validation:  Prints debug messages if invalid only.
        if (!chart2D.validate (false))
            chart2D.validate (true);

        //<-- End Chart2D configuration -->

        //Configure a JFrame GUI
        frame = new JFrame();
        frame.getContentPane().add (chart2D);  //Add Chart2D to GUI
        frame.setTitle (Messages.TITLE);
        frame.addWindowListener (
            new WindowAdapter() {
            @Override
                public void windowClosing (WindowEvent e) {
                destroy();
        } } );

        frame.setPreferredSize(new Dimension(800, 400));
        frame.pack();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation (
        (screenSize.width - frame.getSize().width) / 2,
        (screenSize.height - frame.getSize().height) / 2);

        if (!isApplet)
            start();
    }


    /**
    * Shows the JFrame GUI.
    */
    @Override
    public void start() {
        frame.show();
    }


    /**
    * Ends the application or applet.
    */
    @Override
    public void destroy() {

        if (frame != null) frame.dispose();
//        if (!isApplet) System.exit (0);
    }

    /**
     * This methods fetches data from the database and stores them in the 
     * private variables
     */
    private void query() {
        try{
            ResultSet rs1, rs2;
            Database mysql = (Database) StorageFactory.getStorage(StorageFactory.DBTYPE, Database.MYSQL);
            adminConn = mysql.getConnection(Database.ADMIN);
            Statement stat = adminConn.createStatement();
            String query1 = this.queryNumOfRows;//needs to be a variable
            rs1 = stat.executeQuery(query1);
            String[] arr = null;
            float[] val = null;
            while(rs1.next()) {
                arr = new String[(int)rs1.getInt("numRecords")];
                val = new float[(int)rs1.getInt("numRecords")];
                this.rows = (int)rs1.getInt("numRecords");
//                System.out.println(this.rows);
                break;
            }
            
            String query2 = this.reportQuery;//needs to be a variable
            rs2 = stat.executeQuery(query2);
            int i = 0;
            while(rs2.next()){
//                arr[i] = rs2.getString("ItemName") + "(" + rs2.getString("UPC") + ")";
//                val[i] = (float)rs2.getInt("Quantity");
                arr[i] = rs2.getString(this.param1);//needs to be a variable
                val[i] = (float)rs2.getInt(this.param2);//needs to be a variable
                // to-do: compare val to see if it is null or not; if so set it to 0
//                System.out.println(val[i]);
                i++;
            }
            this.cols = new String[i];
            this.cols = arr;
            this.vals = val;
//            this.results = rs2;
            adminConn.close();
        }
        catch(SQLException e){
            e.printStackTrace();
        }
        catch(ClassNotFoundException e){
            e.printStackTrace();
        }
    }
}
